package cn.szsys.integration.util;

import cn.hutool.core.text.CharSequenceUtil;
import cn.szsys.integration.ex.enums.ExceptionEnum;
import com.alibaba.fastjson2.JSON;
import lombok.Data;

@Data
public class R<T> {
    static final String SUCCESS = "E0000";

    private String sysCode;
    /**
     * 错误信息
     */
    private String msg;
    /**
     * requestId
     */
    private String requestId;
    /**
     * 数据
     */
    private T data;
    /**
     * 计费规则
     */
    private Boolean billed;

    // private Map map = new HashMap(); //动态数据
    //20250330 提示信息没有的时候默认返回操作失败
    public String getMsg() {
        return CharSequenceUtil.isBlank(msg) && !SUCCESS.equals(sysCode) ? ExceptionEnum.OP_FAIL.getMsg() : msg;
    }

    public static <T> R<T> success() {
        R<T> r = new R<T>();
        r.sysCode = SUCCESS;
        r.msg = "操作成功";
        return r;
    }

    public static <T> R<T> success(T object) {
        R<T> r = new R<T>();
        r.data = object;
        r.sysCode = SUCCESS;
        r.msg = "操作成功";
        r.billed = true;
        return r;
    }

    public static <T> R<T> success(T object, Boolean billed) {
        R<T> r = new R<T>();
        r.data = object;
        r.sysCode = SUCCESS;
        r.msg = "操作成功";
        r.billed = billed;
        return r;
    }

    public static <T> R<T> success(T object, String msg, String code) {
        R<T> r = new R<T>();
        r.data = object;
        r.sysCode = code;
        r.msg = msg;
        return r;
    }

    public static <T> R<T> error(ExceptionEnum e) {
        return error(e.getCode(), e.getMsg());
    }

    public static <T> R<T> error(ExceptionEnum e, T data) {
        return error(e.getCode(), e.getMsg(), data);
    }


    public static <T> R<T> error(ExceptionEnum e, String msg, T data) {
        return error(e.getCode(), msg, data);
    }

    public static <T> R<T> error(String code, String msg, T data) {
        R<T> r = new R<>();
        r.sysCode = code;
        r.msg = msg;
        r.data = data;
        r.billed = false;
        return r;
    }

    public static <T> R<T> error(String code, String msg) {
        R<T> r = new R<>();
        r.sysCode = code;
        r.msg = msg;
        return r;
    }

    public static <T> R<T> error(String msg) {
        R<T> r = new R<>();
        r.sysCode = "E9999";
        r.msg = msg;
        return r;
    }

    public boolean isSuccess() {
        return SUCCESS.equals(sysCode);
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
